import groovy.time.*

class FeedInfoController {

  def authenticateService
  def feedCollectorService

  def index = { redirect(action: list, params: params) }

  // the delete, save and update actions only accept POST requests
  static allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

  def list = {
    if (!params.max) params.max = 10
    [feedInfoInstanceList: FeedInfo.list(params)]
  }

  def show = {
    use([org.codehaus.groovy.runtime.TimeCategory] ){
      def feedInfoInstance = FeedInfo.get(params.id)

      if (!feedInfoInstance) {
        flash.message = "Feed not found with id ${params.id}"
        redirect(controller: 'profile', action: 'list')
      }
      else {
        def nextUpdate = feedInfoInstance.lastUpdated + feedInfoInstance.updateFrequency.minutes
        return [feedInfoInstance: feedInfoInstance, nextUpdate: nextUpdate] 
      }
    }
  }

  def delete = {
    def feedInfoInstance = FeedInfo.get(params.id)
    if (feedInfoInstance && (feedInfoInstance.user == authenticateService.userDomain() || authenticateService.ifAllGranted(Role.ADMIN))) {
      def user = feedInfoInstance.user
      feedInfoInstance.delete()
      flash.message = "Feed ${params.id} deleted"
      redirect(controller: 'user', action: 'show', id: user.id)
    }
    else {
      flash.message = "FeedInfo not found with id ${params.id} or no permission to delete feed"
      redirect(action: list)
    }
  }

  def edit = {
    def feedInfoInstance = FeedInfo.get(params.id)

    if (!feedInfoInstance || (feedInfoInstance.user != authenticateService.userDomain() && !authenticateService.ifAllGranted(Role.ADMIN))) {
      flash.message = "Feed not found with id ${params.id} or no permission to change feed"
      redirect(controller: 'profile', action: 'list')
    }
    else {
      return [feedInfoInstance: feedInfoInstance]
    }
  }

  def update = {
    try {
      def feedInfoInstance = FeedInfo.get(params.id)
      if (feedInfoInstance && (feedInfoInstance.user == authenticateService.userDomain() || authenticateService.ifAllGranted(Role.ADMIN))) {
        if (params.version) {
          def version = params.version.toLong()
          if (feedInfoInstance.version > version) {

            feedInfoInstance.errors.rejectValue("version", "feedInfo.optimistic.locking.failure", "Another user has updated this FeedInfo while you were editing.")
            render(view: 'edit', model: [feedInfoInstance: feedInfoInstance])
            return
          }
        }
        feedInfoInstance.properties = params
        if (!feedInfoInstance.hasErrors() && feedInfoInstance.save()) {
          flash.message = "Feed ${params.id} updated"
          redirect(action: show, id: feedInfoInstance.id)
        }
        else {
          render(view: 'edit', model: [feedInfoInstance: feedInfoInstance])
        }
      }
      else {
        flash.message = "Feed not found with id ${params.id} or no permission to update feed"
        redirect(action: edit, id: params.id)
      }
    } catch (org.xml.sax.SAXParseException e) {
      flash.message = "Error: The feed URL you've entered is not a valid RSS2 or Atom Feed."
      render(view: 'edit', model: [feedInfoInstance: feedInfoInstance])
    }
  }

  def create = {
    def feedInfoInstance = new FeedInfo()
    feedInfoInstance.properties = params
    return ['feedInfoInstance': feedInfoInstance]
  }

  def save = {
    try {
      def feedInfoInstance = new FeedInfo(params)
      if (!feedInfoInstance.hasErrors() && feedInfoInstance.save()) {
        def msg = flash.message = feedCollectorService.updateFeed(feedInfoInstance)
        flash.message = "Feed ${feedInfoInstance.id} created and ${msg}"
        redirect(action: show, id: feedInfoInstance.id)
      }
      else {
        render(view: 'create', model: [feedInfoInstance: feedInfoInstance])
      }
    } catch (org.xml.sax.SAXParseException e) {
      flash.message = "Error: The feed URL you've entered is not a valid RSS2 or Atom Feed."
      render(view: 'create', model: [feedInfoInstance: feedInfoInstance])
    }
  }

  def updateFeed = {
    def feedInfoInstance = FeedInfo.get(params.id)
    if (feedInfoInstance && (feedInfoInstance.user == authenticateService.userDomain() || authenticateService.ifAllGranted(Role.ADMIN))) {
      flash.message = feedCollectorService.updateFeed(feedInfoInstance)
      redirect (controller: 'message', action: 'all')
    } else {
      flash.message = "Feed not found with id ${params.id} or no permission to update feed"
      redirect(action: 'edit', id: params.id)      
    }
  }
}
